<template>
	<view class="repair-container">
		<!-- 搜索栏 -->
		<up-search
			v-model="searchKeyword"
			placeholder="请输入设备名称或编号"
			:show-action="true"
			action-text="搜索"
			@search="handleSearch"
			@custom="handleSearch"
			bg-color="#f5f5f5"
			shape="square"
		></up-search>

		<!-- 报修设备按钮 -->
		<view class="add-repair-btn">
			<up-button
				type="primary"
				icon="plus"
				text="报修设备"
				@click="navigateToAddRepair"
			></up-button>
		</view>

		<!-- 维修记录列表 -->
		<view class="repair-list">
			<up-list
				@scrolltolower="loadMore"
				v-if="repairList.length > 0"
			>
				<up-list-item
					v-for="(item, index) in repairList"
					:key="item.id"
				>
					<view class="repair-item">
						<view class="item-header">
							<text class="device-name">{{
								item.deviceName
							}}</text>
							<up-tag
								:text="getStatusText(item.repairStatus)"
								:type="getStatusType(item.repairStatus)"
								size="mini"
							/>
						</view>

						<view class="item-content">
							<text class="content-text"
								>报修设备:
								{{
									equipmentList.find(
										(res) =>
											res.equipmentId === item.equipmentId
									)?.name
								}}</text
							>
							<text class="content-text"
								>故障类型:
								{{
									fultTypeList[0].find(
										(res) => item.faultType == res.id
									)?.label
								}}</text
							>
							<text class="content-text"
								>报修人: {{ item.reporter }}</text
							>
							<text class="content-text"
								>报修时间: {{ item.reportTime }}</text
							>
							<text class="content-text"
								>位置:
								{{
									equipmentList.find(
										(res) =>
											res.equipmentId === item.equipmentId
									)?.location
								}}</text
							>
							<text class="content-text"
								>故障描述: {{ item.faultDescription }}</text
							>
						</view>

						<view class="item-footer">
							<up-button
								v-if="item.repairStatus == '1'"
								type="error"
								size="small"
								text="撤销报修"
								@click="handleCancelRepair(item)"
							></up-button>

							<up-button
								type="primary"
								size="small"
								text="查看详情"
								@click="
									navigateToDetail(item.repairId, true)
								"
							></up-button>

							<up-button
								v-if="item.repairStatus == '1' || item.repairStatus == '2'"
								type="success"
								size="small"
								text="进行维修"
								@click="
									navigateToDetail1(
										item.repairId,
										false,
										item
									)
								"
							></up-button>
						</view>
					</view>
				</up-list-item>
			</up-list>

			<!-- 空状态 -->

			<!-- 加载更多 -->
			<up-loadmore
				style="margin-bottom: 20rpx"
				:status="loadStatus"
				v-if="repairList.length > 0"
			/>
		</view>
	</view>
</template>

<script setup>
import { ref, onMounted, onActivated } from "vue";
import {
	onLoad,
	onReachBottom,
	onShow,
	onPullDownRefresh
} from "@dcloudio/uni-app";
import { formatTime } from "@/utils/date";
import {
	listRepair,
	getRepair,
	delRepair,
	addRepair,
	updateRepair,
	repairEquipment,
	listEquipment
} from "@/api/repair";
import dayjs from "dayjs";

const equipmentList = ref([]);
async function getEquipmentList() {
	const res = await listEquipment({
		pageNum: 1,
		pageSize: 100
	});
	equipmentList.value = res.data.rows;
}

const fultTypeList = ref([
	[
		{ label: "机械故障", id: "1" },
		{ label: "电气故障", id: "2" },
		{ label: "软件故障", id: "3" },
		{ label: "人为损坏", id: "4" },
		{ label: "自然老化", id: "5" }
	]
]);

// 维修状态枚举
const REPAIR_STATUS = {
	PENDING: "1", // 待处理
	PROCESSING: "2", // 处理中
	COMPLETED: "3", // 已完成
	CANCELLED: "4" // 已取消
};

// 搜索关键词
const searchKeyword = ref("");
// 维修列表数据
const repairList = ref([]);
// 分页参数
const pagination = ref({
	page: 1,
	pageSize: 10,
	total: 0
});
// 加载状态
const loadStatus = ref("loadmore");

// 初始化加载数据
onMounted(() => {
	// fetchRepairList();
	getEquipmentList();
});

onShow(() => {
	fetchRepairList(true);
});

// 上拉加载更多
onReachBottom(() => {
	if (loadStatus.value !== "nomore") {
		loadMore();
	}
});

// 下拉刷新
onPullDownRefresh(() => {
	fetchRepairList(true);
});

// 获取维修列表
const fetchRepairList = async (reset = false) => {
	if (reset) {
		pagination.value.page = 1;
		repairList.value = [];
		loadStatus.value = "loading";
	} else {
		// loadStatus.value = "loading";
	}

	try {
		// 模拟API请求
		const mockData = await listRepair({
			pageNum: pagination.value.page,
			pageSize: pagination.value.pageSize
		});

		uni.stopPullDownRefresh();

		if (reset) {
			repairList.value = mockData.data.rows;
		} else {
			repairList.value = [
				...repairList.value,
				...mockData.data.rows
			];
		}

		pagination.value.total = mockData.data.total;

		// 更新加载状态
		if (repairList.value.length >= pagination.value.total) {
			loadStatus.value = "nomore";
		} else {
			loadStatus.value = "loadmore";
			pagination.value.page++;
		}
	} catch (error) {
		console.error("获取维修列表失败:", error);
		loadStatus.value = "loadmore";
		uni.showToast({
			title: "获取数据失败",
			icon: "none"
		});
	}
};

// 搜索处理
const handleSearch = () => {
	fetchRepairList(true);
};

// 加载更多
const loadMore = () => {
	if (loadStatus.value === "nomore") return;
	fetchRepairList();
};

// 跳转到新增报修页面
const navigateToAddRepair = () => {
	uni.navigateTo({
		url: "/pages/repair/add"
	});
};

const navigateToDetail = (id, detail) => {
	uni.navigateTo({
		url: `/pages/repair/detail?id=${id}&detail=${detail}`
	});
};

// 跳转到详情页面
const navigateToDetail1 = (id, detail, row) => {
	if (row.repairStatus == 2) {
		uni.navigateTo({
			url: `/pages/repair/detail?id=${id}&detail=${detail}`
		});
		return
	}
	uni.showModal({
		title: "提示",
		content: "是否确认开始维修",
		success: async (res) => {
			if (res.confirm) {
				await updateRepair({
					...row,
					repairStatus: "2",
					startTime: dayjs().format("YYYY-MM-DD")
				});
				uni.navigateTo({
					url: `/pages/repair/detail?id=${id}&detail=${detail}`
				});
			}
		}
	});
};

// 撤销报修
const handleCancelRepair = (row) => {
	uni.showModal({
		title: "提示",
		content: "确定要撤销此报修记录吗？",
		success: async (res) => {
			if (res.confirm) {
				await repairEquipment({
					...row,
					repairStatus: "3"
				});
				fetchRepairList(true);
				uni.showToast({
					icon: "none",
					title: "撤销成功"
				});
			}
		}
	});
};

// 获取状态文本
const getStatusText = (status) => {
	switch (status) {
		case REPAIR_STATUS.PENDING:
			return "待受理";
		case REPAIR_STATUS.PROCESSING:
			return "维修中";
		case REPAIR_STATUS.COMPLETED:
			return "已修复";
		case REPAIR_STATUS.CANCELLED:
			return "无法维修";
		default:
			return "未知状态";
	}
};

// 获取状态标签类型
const getStatusType = (status) => {
	switch (status) {
		case REPAIR_STATUS.PENDING:
			return "warning";
		case REPAIR_STATUS.PROCESSING:
			return "primary";
		case REPAIR_STATUS.COMPLETED:
			return "success";
		case REPAIR_STATUS.CANCELLED:
			return "info";
		default:
			return "default";
	}
};
</script>

<style lang="scss" scoped>
.repair-container {
	padding: 20rpx;
	display: flex;
	flex-direction: column;

	.add-repair-btn {
		margin: 20rpx 0;
	}

	.repair-list {
		flex: 1;
		overflow: hidden;

		.repair-item {
			background-color: #fff;
			border-radius: 12rpx;
			padding: 24rpx;
			margin-bottom: 20rpx;
			box-shadow: 0 2rpx 10rpx rgba(0, 0, 0, 0.05);

			.item-header {
				display: flex;
				justify-content: space-between;
				align-items: center;
				margin-bottom: 16rpx;

				.device-name {
					font-size: 32rpx;
					font-weight: bold;
					color: #333;
				}
			}

			.item-content {
				margin-bottom: 20rpx;

				.content-text {
					display: block;
					font-size: 26rpx;
					color: #666;
					line-height: 1.6;
				}
			}

			.item-footer {
				display: flex;
				justify-content: flex-end;
				gap: 20rpx;
			}
		}
	}
}
</style>
